Is there any way to simplify this function in java script